package container

import (
	"adai.design/homemaster/container/accessory"
	"adai.design/homemaster/container/service"
	"errors"
	"io/ioutil"
	"encoding/json"
	"adai.design/homemaster/log"
	"runtime"
	"os"
)

type HomeMasterV2 struct {
	*Container							`json:"-"`
	Homemaster *accessory.HomeMasterV2	`json:"-"`

	// 子设备管理
	// 当子设备增加或者减少时，版本号+1
	Version 		int 		`json:"version"`
	Accs 			[]string	`json:"accessories"`
}

func (h *HomeMasterV2) configFile() string {
	if runtime.GOARCH != "mipsle" {
		path := os.Getenv("GOPATH") + "/src/adai.design/homemaster/build/tmp/"
		file := path + "container.cfg"
		return file
	}
	return "/etc/homemaster/container.cfg"
}

func (h *HomeMasterV2) save() error {
	data, err := json.MarshalIndent(h, "", "    ")
	if err != nil {
		return err
	}
	log.Info("homemaster config:\n %s", string(data))
	return ioutil.WriteFile(h.configFile(), data, 0666)
}

func (h *HomeMasterV2) load() error {
	data, err := ioutil.ReadFile(h.configFile())
	if err != nil {
		log.Error("%s", err)
		return err
	}
	err = json.Unmarshal(data, h)
	if err != nil {
		log.Error("%s", err)
		return err
	}

	h.Container.Version = h.Version
	log.Notice("container config: %s", string(data))
	return nil
}

// 检查设备列表是否变化
func (h *HomeMasterV2) versionCheck(aid string, add bool) bool {
	if add {
		for _, v := range h.Accs {
			if v == aid {
				return false
			}
		}
		h.Accs = append(h.Accs, aid)
		h.Version += 1
		if h.save() == nil {
			h.Container.SetVersion(h.Version)
		}
		return true
	}

	if !add {
		for i, v := range h.Accs {
			if v == aid {
				h.Accs = append(h.Accs[:i], h.Accs[i+1:]...)
				h.Version += 1
				if h.save() == nil {
					h.Container.SetVersion(h.Version)
				}
				return true
			}
		}
	}
	return false
}

var HomeMasterUUID = func() string {
	var buf []byte
	var err error
	if runtime.GOARCH == "mipsle" {
		buf, err = ioutil.ReadFile("/etc/homemaster/register")
	}else {
		buf, err = ioutil.ReadFile("build/files/etc/homemaster/register")
	}

	var register map[string]interface{}
	err = json.Unmarshal(buf, &register)
	if err != nil {
		return ""
	}

	if v, ok := register["uuid"]; ok {
		return v.(string)
	}
	return ""
}()

func NewHomeMasterV2() *HomeMasterV2 {
	container := &HomeMasterV2{}

	container.Container = NewContainer()

	container.Homemaster = accessory.NewHomeMasterV2(HomeMasterUUID)
	container.Container.AddAccessory(container.Homemaster.Accessory)
	container.load()
	return container
}

func (h *HomeMasterV2) AddService(s *service.Service, sid int) error {
	h.Homemaster.AddService(s, sid)
	return nil
}

func (h *HomeMasterV2) RemoveService(sid int) error {
	h.Homemaster.RemoveService(sid)
	return nil
}

// 全局变量
var HomeMaster = NewHomeMasterV2()

func GetContainer() *Container {
	return HomeMaster.Container
}

func AddService(s *service.Service, sid int) error {
	HomeMaster.Homemaster.AddService(s, sid)
	return nil
}

func RemoveService(sid int) error {
	HomeMaster.Homemaster.RemoveService(sid)
	return nil
}

func AddAccessory(a *accessory.Accessory) error {
	for _, v := range HomeMaster.Accessories {
		if v.UUID == a.UUID {
			return errors.New("accessory already exists")
		}
	}
	log.Notice("container accessory(%s) type(%d) insert!", a.UUID, a.Type)
	HomeMaster.Accessories = append(HomeMaster.Accessories, a)
	HomeMaster.versionCheck(a.UUID, true)
	return nil
}

func RemoveAccessoryByAid(aid string) error {
	var acc *accessory.Accessory
	for _, v := range HomeMaster.Accessories {
		if v.UUID == aid {
			acc = v
		}
	}
	return RemoveAccessory(acc)
}

func RemoveAccessory(a *accessory.Accessory) error {
	if a == nil {
		return errors.New("invalid")
	}
	for i, v := range HomeMaster.Accessories {
		if a.UUID == v.UUID {
			HomeMaster.Accessories = append(HomeMaster.Accessories[:i], HomeMaster.Accessories[i+1:]...)
			HomeMaster.versionCheck(a.UUID, false)
			return nil
		}
	}
	return errors.New("accessory does not exits")
}



















